<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Crontab;

use App\Model\AncientPoetry;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use QL\QueryList;
use Swoole\Timer;

//#[Crontab(rule: '*/50 * * * * *', name: 'ancient_poetry', callback: 'execute', memo: '古诗词抓取')]
class AncientPoetryCrontab
{
    // 平台链接
    protected string $ancient_poetry_url = 'https://www.gushiwen.cn';

    // 类型
    protected array $ancient_poetry_type = [];

    // 作者
    protected array $ancient_poetry_author = [];

    // 朝代
    protected array $ancient_poetry_dynasty = [];

    // 形式
    protected array $ancient_poetry_form = [];

    #[Inject]
    private StdoutLoggerInterface $logger;

    public function execute()
    {
        $this->getPoetryProseAuthorConnectLists();
    }

    /**
     * 推荐.一级分类--作者--朝代.
     */
    protected function getAncientPoetryScreen(): array
    {
        $url = $this->ancient_poetry_url . '/shiwens/';
        $data_query = QueryList::get($url);
        $list = [];
        for ($i = 1; $i <= 3; ++$i) {
            // DOM解析文章标题
            $names = $data_query->find('#type' . $i . '>.sright>a')->texts();
            // DOM解析文章作者
            $urls = $data_query->find('#type' . $i . '>.sright>a')->attrs('href');
            $count = count($names);
            $add = [];
            for ($j = 0; $j < $count; ++$j) {
                $add[] = ['name' => $names[$j], 'url' => $this->ancient_poetry_url . $urls[$j]];
            }
            $type_name = 'type';
            if ($i == 2) {
                $type_name = 'author';
            } elseif ($i == 3) {
                $type_name = 'dynasty';
            }
            $list[$type_name] = $add;
        }
        return $list;
    }

    /**
     * 获取二级类型列表.
     */
    protected function getPoetryProseTypes(): array
    {
        $url = $this->ancient_poetry_url . '/gushi/shijing.aspx';
        $data_query = QueryList::get($url);
        // DOM解析文章标题
        $names = $data_query->find('.typecont>span>a')->texts();
        // DOM解析文章作者
        $urls = $data_query->find('.typecont>span>a')->attrs('href');
        $count = count($names);
        $lists = [];
        for ($j = 0; $j < $count; ++$j) {
            $lists[] = ['name' => $names[$j], 'url' => $this->ancient_poetry_url . $urls[$j]];
        }
        return $lists;
    }

    protected function getPoetryProseAuthorConnectLists()
    {
        $container = ApplicationContext::getContainer();
        // 通过 DI 容器获取或直接注入 RedisFactory 类
        $redis = $container->get(Redis::class);
        $author_list=[];
        if ($redis->get('author_list')){
            $author_list = json_decode($redis->get('author_list'),true);
            if (empty($author_list)){
                $data = $this->getAncientPoetryScreen();
                $author_list = $data['author'];
                $redis->set('author_list',json_encode($author_list));
            }
        }
        $author_text=$redis->get('author');
        if (empty($author_text) && $author_list){
            $author_array = array_column($author_list,'name');
            $author_text = $author_array[array_rand($author_array)];
            $redis->set('author',$author_text);
        }
        $timer_id = Timer::tick(30000, function () use (&$timer_id,$author_text,$redis,$author_list) {
            static $page = 1;
            $url = "https://www.gushiwen.cn/shiwens/default.aspx?page={$page}&tstr=&astr={$author_text}&cstr=&xstr=";
            $data_query = QueryList::get($url);
            // DOM解析文章标题
            $names = $data_query->find('.sons>.cont>div>p>a>b')->texts();
            if ($page==8) {
                $redis->del('author_list');
                if ($author_list){
                    $new_array = array_filter($author_list,function ($value)use($author_text){
                        return $value!=$author_text;
                    });
                    if ($new_array){
                        $redis->set('author_list',json_encode($new_array));
                    }
                }
                Timer::clear($timer_id);
                $redis->del('author');
                return true;
            }
            // DOM解析文章作者
            $urls = $data_query->find('.sons>.cont>div>p>a')->attrs('href');
            $author = $data_query->find('.sons>.cont>div>.source')->texts();
            $author_img = $data_query->find('.sons>.cont>div>.source>a>img')->attrs('src');
            $connect = $data_query->find('.sons>.cont>div>.contson')->texts();
            $count = count($names);
            $lists = [];
            $date_time = date('Y-m-d H:i:s');
            for ($j = 0; $j < $count; ++$j) {
                $exists = AncientPoetry::query()->where(['name' => $names[$j], 'author' => $author[$j]])->exists();
                if (empty($exists)) {
                    $lists[] = [
                        'name' => $names[$j],
                        'url' => $this->ancient_poetry_url . $urls[$j],
                        'author' => $author[$j],
                        'author_img' => $author_img[$j],
                        'connect' => $connect[$j],
                        'created_at' => $date_time,
                        'updated_at' => $date_time,
                    ];
                }
            }
            if ($lists) {
                AncientPoetry::query()->insert($lists);
            }
            ++$page;
            return true;
        });
    }
}
